<?php


namespace api\zmt\controller;

use cmf\controller\RestBaseController;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Filesystem;

class UploadController extends RestBaseController
{


    //头像、上传图片,文件
    public function upload(){
        //获取表单上传文件
        $file = request()->file('file');
        //上传到本地的服务器
        $result = Filesystem::disk('public')->putFile('file',$file);
        if($result){
            $this->success('上传成功',['url'=>request()->domain().DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.$result]);
        }
        $this->error('上传失败');
    }


    public function Qiniu()
    {
        $file = request()->file('file');
        if(!$file) {
            halt('file error');
        }
        // 七牛云配置
        $accessKey = config('app.qiniuOss.accessKey');
        $secretKey = config('app.qiniuOss.secretKey');
        $bucket = config('app.qiniuOss.bucket');
        // 构建鉴权对象
        $auth = new Auth($accessKey,$secretKey);
        //生成上传Token
        $token = $auth->uploadToken($bucket);

        //要上传文件的本地路径
        $filePath = $file->getPathname();

        //上传到储存后保存的文件名
        $key = time() . '.' . $file->getOriginalExtension();

        //构建UploadManager对象
        $uploadMgr = new UploadManager();
        //调用UploadManager的putFile方法进行文件的上传
        list($return, $error) = $uploadMgr->putFile($token, $key, $filePath);
        if ($error !== null) {
            //$this->error('上传失败');
            halt($error->message());
        } else {
            //var_dump($ret);
            $this->success('上传成功',[
                'url' => ''.$return['key'],
            ]);
        }
    }
}